import Ember from 'ember';

// http://guides.emberjs.com/v1.13.0/enumerables/

export default Ember.Controller.extend({
  selectedItem: Ember.computed('model.@each.isSelected', function() {
    var model = this.get('model');
    return model.find(function(m){
      return m.get('isSelected');
    });
  }),
  confirming: false,
  count: Ember.computed('model', function(){
    // console.log(this.get('model'));
  }),
  actions: {
    createNew() {
      var store = this.store,
          self = this;

        Ember.$.ajax({
          method: 'POST',
          url: "/api/v1/keypairs",
          contentType: 'application/json; charset=UTF-8',
          data: "{}",
        })
        .done(function(data, textStatus, jqXHR){
          var location = jqXHR.getResponseHeader("location") || "",
              idx = location.lastIndexOf("/") || 0,
              id = location.substring(idx + 1);
          // console.log(id);
          store.findRecord("keypair", id).then(function(kp){
            self.set('model', store.peekAll("keypair"));
          });
        })
        .fail(function(qXHR, textStatus, errorThrown){
          //  console.log('keypairs create failed.');
        })
        .always(function(){
          //  console.log('keypair create over.');
        });
    },
    itemSelectChange(kp) {
      var kpOldSelected = kp.get('isSelected');
      this.get('model').forEach(i => i.set('isSelected', false)); // deselect all
      kp.set('isSelected', !kpOldSelected);
    },
    aboutDeleteItem() {
      var kp =  this.get('selectedItem'),
          confirming = this.get('confirming');
      if (kp) {
        this.set('confirming', !confirming);
      }
    },
    deleteItem() {
      var kp =  this.get('selectedItem');
      if (kp) {
        this.store.deleteRecord(kp);
        kp.save();
        this.set('confirming', false);
      }
    }
  }
});
